package weaver.batchchanges.util;

import com.alibaba.fastjson.JSON;
import org.json.JSONObject;
import weaver.conn.RecordSet;

import java.util.*;

/**
 * cmd查询sql后的结果操作工具类
 */
public class CmdResultUtil {

    /**
     * 将查询结果集返回成List<Map<String, Object>>形式封装
     * @param rs
     * @return
     */
    public static List<Map<String, Object>> getListMapResult(RecordSet rs) {
        //获取所有列名
        String[] columnNames = rs.getColumnName();
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();

        if (columnNames != null && columnNames.length > 0) {
            //获取查询到的数据列表
            Vector<Object[]> dataArray = rs.getArray();
            //遍历列表
            for (Object[] data : dataArray) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 0; i < columnNames.length; i++) {
                    map.put(columnNames[i], data[i]);
                }
                resultList.add(map);
            }
        }
//        List<Map<String, Object>> result = getResult(rs,new TypeReference<Map<String, Object>>() {});
        return resultList;
    }


    /**
     * 将查询结果集返回成指定类的列表形式封装
     * @param rs
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> List<T> getResult(RecordSet rs, Class<T> clazz) {
        //获取所有列名
        String[] columnNames = rs.getColumnName();
        List<T> resultList = new ArrayList<T>();

        if (columnNames != null && columnNames.length > 0) {
            //获取查询到的数据列表
            Vector<Object[]> dataArray = rs.getArray();
            //遍历列表
            for (Object[] data : dataArray) {
                Map<String, Object> map = new HashMap<String, Object>();
                for (int i = 0; i < columnNames.length; i++) {
                    map.put(columnNames[i], data[i]);
                }
                String jsonString = new JSONObject(map).toString();
                T t = JSON.parseObject(jsonString, clazz);
                resultList.add(t);
            }
        }
        return resultList;
    }
}
